﻿using BeginEndMarkReceiveFilter_Client;
using SuperSocket.ClientEngine;
using SuperSocket.ProtoBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using WinServer;

namespace BeginEndMarkReceiveFilter
{
    class socketClient
    {
        static EasyClient<MyPackageInfo> client = null;
        /// 定义服务端的ip地址和端口，以及接收数据的头和尾，只有在头和尾之间的数据才算有效数据
        /// </summary>
        /// <param name="ip">ip地址</param>
        /// <param name="port">服务端口</param>
        /// <param name="startFilter">数据头</param>
        /// <param name="endFilter">数据尾</param>
        string ip;
        int port;
        string startFilter = "";
        string endFilter = "";
        bool cycleSend = false;
        bool connected = false;

        public socketClient(string ip, int port, string startFilter, string endFilter)
        {
            this.ip = ip;
            this.port = port;
            if (!string.IsNullOrEmpty(startFilter)) this.startFilter = startFilter;
            if (!string.IsNullOrEmpty(endFilter)) this.endFilter = endFilter;
            client = new EasyClient<MyPackageInfo>();
            client.Initialize(new MyBeginEndMarkReceiveFilter(startFilter,endFilter));
            client.Connected += OnClientConnected;
            client.NewPackageReceived += OnPackageReceived;
            // client.Error += OnClientError;
            // client.Closed += OnClientClosed;
           

        }

        private void OnClientClosed(object sender, EventArgs e)
        {
            Console.WriteLine("关闭连接...");
        }

        

        private void OnPackageReceived(object sender, PackageEventArgs<MyPackageInfo> e)
        {
            Console.WriteLine("已接收："+e.Package.Body);
           
        }

        private void OnClientConnected(object sender, EventArgs e)
        {
            Console.WriteLine("已连接到服务器...");
        }


        /// 要发送到服务端的数据
        /// </summary>
        public string data { get; set; } = "hello,this is super client\r\n";
    
        /// 开始循环发送数据       
        public void startComm()
        {
            cycleSend = true;
            System.Threading.Thread _thread = new System.Threading.Thread(sendData);
            _thread.IsBackground = true;
            _thread.Start();
        }     
        /// 采用线程间隔一秒发送数据，防止界面卡死     
        public void sendData()
        {
            while (cycleSend)
            {
                if (!client.IsConnected)
                {
                   connectToServer(ip, port);
                }
                if (client.IsConnected)
                {
                    client.Send(Encoding.ASCII.GetBytes(startFilter + data+ endFilter));
                }
                System.Threading.Thread.Sleep(2000);
            }
        }
    
        /// 停止循环发送数据     
        public void stopComm()
        {
            cycleSend = false;
        }
      
        /// 连接到服务端
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public async void connectToServer(string ip, int port)
        {
            connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Parse(ip), port));
            //if (!connected)
            //{
            //    connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Parse(ip), port));
            //}           
            //if (connected && client!=null)
            //{
            //    //发送连接信息
           // Console.Out.WriteLine(client.IsConnected);
            //if (client.IsConnected) client.Send(Encoding.ASCII.GetBytes(startFilter+"build connection" + endFilter));
            //}
        }
       
    }
}
